<template>
    <div class="search">
        <div class="header">
            <div class="back" @click.once="back">
                <i class="iconfont icon-arrow-left"></i>
            </div>
            <div class="search-box-wrapper">
                <transition appear name="scale">
                    <search-box
                        :inputValue="inputValue"
                        @query="onInputChange"
                        @clear="clear"
                        @search="doSearch"
                        ref="searchBox"
                    >
                    </search-box>
                </transition>
            </div>
        </div>
        <transition appear name="moveup">
            <scroll class="shortcut-wrapper"
                    :data="allData"
                    ref="scroll"
                    :beforeScroll=beforeScroll
                    @beforeScroll="blurInput"
            >
                <div class="shortcut" ref="shortcut">
                    <div class="search-history"
                         :class="{'fold': isFold}"
                         v-show="hasSearchHistory"
                    >
                        <div class="title">
                            <span class="text">搜索历史</span>
                            <span class="clear" @click="clearHistory">
                                <i class="iconfont icon-trash"></i>
                            </span>
                        </div>
                        <div class="history-content" ref="historyContent">
                            <ul class="history-list">
                                <span class="item"
                                      v-for="(item, index) in searchHistory"
                                      :key="index"
                                      @click="doSearch(item)"
                                      ref="item"
                                >
                                    <span>{{item}}</span>
                                </span>
                                <li class="item fold-btn iconfont icon-up"
                                    @click="changeFold(true)"
                                    v-show="!isFold && needFold"
                                >
                                </li>
                            </ul>
                            <p class="unfold-btn iconfont icon-down"
                               @click="changeFold(false)"
                               ref="unfoldBtn"
                               v-show="isFold && needFold"
                            >
                            </p>
                        </div>
                    </div>
                    <div class="hot-key">
                        <h1 class="title">热门搜索</h1>
                        <ul class="key-list">
                            <li class="item"
                                v-for="(item, index) in hotKey"
                                :key="index"
                                @click="doSearch(item.k)"
                            >
                                <span class="num" :class="{'hot': index < 3}">{{index + 1}}</span>
                                <span class="name">{{item.k}}</span>
                                <span class="listen-num">{{item.n}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </scroll>
        </transition>
        <div class="search-suggest" v-show="inputValue && !isShowResult" ref="result">
            <suggest :query="inputValue"
                     @listScroll="blurInput"
                     @select="doSearch"
            >
            </suggest>
        </div>
        <div class="search-result-wp" v-if="inputValue && isShowResult">
            <search-result @listScroll="blurInput" :searchKey="searchKey">
            </search-result>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import SearchBox from 'base/search-box/search-box'
    import SearchResult from 'components/search-result/search-result'
    import Scroll from 'base/scroll/scroll'
    import Load from 'base/load/load'
    import Suggest from 'components/suggest/suggest'
    // import Confirm from 'base/confirm/confirm'
    import { getStyle } from 'common/js/dom'
    import { getHotKey } from 'api/search'
    import { ERR_OK } from 'api/config'
    import { mapActions, mapGetters } from 'vuex'
    import TabMixin from 'common/mixins/tab'
    import PlayListMixin from 'common/mixins/play-list'
    import { MINI_PLAYER_HEIGHT } from 'common/js/config'
    import ConfirmOption from 'common/js/classes/confirm-option'

    import { Trim } from 'common/js/util'

    const HISTORY_LINE_HEIGHT = 40
    const HISTORY_ITEM_MARGIN = 10
    const UNFOLD_BTN_WIDTH = 29

    export default {
        name: 'search',
        mixins: [TabMixin, PlayListMixin],
        data() {
            return {
                hotKey: [],
                inputValue: '',
                isFold: true,
                needFold: false,
                isShowResult: false,
                searchKey: '',
                beforeScroll: true
            }
        },
        created() {
            this._getHotKey()
            setTimeout(() => {
                this.checkIfNeedFold()
                this.setHistoryOption()
            }, 200)
        },
        computed: {
            hasSearchHistory() {
                return this.searchHistory.length > 0
            },
            // 将搜索历史、搜索历史的折叠状态、热门搜索整合为一个数组
            // 便于scroll组件监听并根据其变化动态刷新
            allData() {
                return this.searchHistory.concat(this.isFold, this.hotKey)
            },
            ...mapGetters([
                'searchHistory'
            ])
        },
        methods: {
            _getHotKey() {
                getHotKey().then((res) => {
                    if (res.code === ERR_OK) {
                        this.hotKey = res.data.hotkey.slice(0, 20)
                    }
                }).catch(() => {
                    this.isLoadErr = true
                })
            },
            back() {
                this.$router.back()
            },
            clearHistory() {
                console.log(this.clearSearchHistory)
                this.showConfirm(new ConfirmOption({
                    msg: '是否清空所有搜索历史',
                    comfirmBtnMsg: '清空',
                    cancelBtnMsg: '取消',
                    handle: this.clearSearchHistory
                }))
            },
            // 改变搜索历史折叠状态
            changeFold(value) {
                this.isFold = value
            },
            // 检测搜索框高度是否足够以判断是否需要折叠
            checkIfNeedFold() {
                if (!this.hasSearchHistory) {
                    return
                }

                let height = this.$refs.historyContent.offsetHeight
                if (height > HISTORY_LINE_HEIGHT) {
                    this.needFold = true
                } else {
                    this.needFold = false
                }
            },
            // 设置展开按钮偏移和搜索历史长度限制
            setHistoryOption() {
                if (!this.needFold) {
                    return
                }

                // 设置展开按钮的位置
                let itemsWidth = this.countItemWidth()
                let listWidth = this.$refs.historyContent.offsetWidth - UNFOLD_BTN_WIDTH
                for (let i = 0, len = itemsWidth.length; i < len; i++) {
                    if (itemsWidth[i] > listWidth && itemsWidth[i - 1] < listWidth) {
                        let x = itemsWidth[i - 1] - listWidth
                        let value = `translateX(${x}px)`
                        getStyle(this.$refs.unfoldBtn, 'transform', value, true)
                    }
                }
                // 限制搜索历史长度
                let listLineWidth = this.$refs.historyContent.offsetWidth
                let contentMax = listLineWidth * 4
                for (let i = 0, len = itemsWidth.length; i < len; i++) {
                    if (itemsWidth[i] > contentMax) {
                        getStyle(this.$refs.item[i], 'display', 'none')
                    }
                }
            },
            // 计算每个搜索历史元素的宽度和
            countItemWidth() {
                let items = this.$refs.item
                let res = []
                let width = 0
                for (let item of items) {
                    width += item.offsetWidth + HISTORY_ITEM_MARGIN
                    res.push(width)
                }
                return res
            },
            // 监听搜索栏输入值
            onInputChange(value) {
                if (value === this.inputValue) {
                    return
                }
                this.inputValue = value
                this.isShowResult = false
            },
            clear() {
                this.inputValue = ''
                this.isShowResult = false
            },
            blurInput() {
                this.$refs.searchBox.blur()
            },
            doSearch(text) {
                if (!text) {
                    return
                }
                const key = Trim(text)
                this.inputValue = key
                this.saveSearchHistory(this.inputValue)

                this.isShowResult = true
                this.searchKey = key
            },
            // 重设滚动部分底部距离
            handlePlayList(playList) {
                const bottom = playList.length > 0 ? `${MINI_PLAYER_HEIGHT + 30}px` : ''
                const el = this.$refs.shortcut
                getStyle(el, 'paddingBottom', bottom)
                this.$refs.scroll.refresh()
            },
            ...mapActions([
                'saveSearchHistory',
                'clearSearchHistory',
                'showConfirm'
            ])
        },
        watch: {
            searchHistory(newValue) {
                if (!newValue) {
                    return
                }
                // 保证设置时dom元素已渲染
                setTimeout(() => {
                    this.checkIfNeedFold()
                    this.setHistoryOption()
                }, 250)
            }
        },
        components: {
            SearchBox,
            Scroll,
            Load,
            Suggest,
            // Confirm,
            SearchResult
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import "~common/stylus/variable"
    @import "~common/stylus/mixin"

    .search
        position: fixed
        top: 0
        bottom: 0
        left: 0
        right: 0
        background: $color-background
        z-index: 100
        .header
            display: flex
            padding: 20px 10px 10px
            .back
                display: block
                line-height: 31px
                font-size: $font-size-large-l
            .search-box-wrapper
                flex: 1
                margin: 0 10px
            .scale-enter-active, .scale-leave-active
                transition: all .3s
            .scale-enter, .scale-leave-to
                transform: scaleX(.6)

        .moveup-enter-active
            transition: all .3s
        .moveup-enter
            transform: translateY(150px)

        .shortcut-wrapper
            position: fixed
            top: 61px
            bottom: 0
            padding-top: 10px
            width: 100%
            overflow: hidden
            .shortcut
                padding-bottom: 30px
                .search-history
                    overflow: hidden
                    margin: 0 25px 20px 25px
                    &.fold
                        height: 73px
                    .title
                        display: flex
                        margin-bottom: 20px
                        .text
                            flex: 1
                            display: inline-block
                            font-weight: bold
                            font-size: $font-size-medium-x
                            color: $color-text
                        .clear
                            extend-click()
                            .icon-trash
                                color: $color-text-d
                    .history-content
                        display: flex
                        .history-list
                            flex: 1
                            display: flex
                            flex-wrap: wrap
                            overflow: hidden
                        .unfold-btn, .history-list > .item
                            display: block
                            padding: 7px 10px
                            margin: 0 10px 10px 0
                            border-radius: 15px
                            no-wrap()
                            background: $color-background-w
                            font-size: $font-size-small-x
                            color: $color-text
                            &:last-child
                                margin-right: 0
                        .unfold-btn, .history-list > .fold-btn
                            box-sizing: border-box
                            display: block
                            padding: 0
                            flex: 0 0 27px
                            margin-right: 0
                            width: 27px
                            height: 27px
                            line-height: 27px
                            text-align: center
                            font-weight: bold
                            color: $color-text-d
                .hot-key
                    position: relative
                    margin: 0 25px
                    .title
                        margin-bottom: 20px
                        font-weight: bold
                        font-size: $font-size-medium-x
                        color: $color-text
                    .item
                        display: flex
                        height: 20px
                        margin-bottom: 20px
                        line-height: 20px
                        .num, .name, .listen-num
                            display: block
                        .num
                            flex: 0 0 15px
                            margin-right: 20px
                            text-align: center
                            color: $color-text-d
                            &.hot
                                color: red
                        .name
                            flex: 1
                            color: $color-text
                        .listen-num
                            flex: 0 0 55px
                            text-align: right
                            font-size: $font-size-small
                            color: $color-text-d
        .search-suggest, .search-result
            position: fixed
            width: 100%
            top: $height-header
            bottom: 0
            overflow: hidden
            background: $color-background
            z-index: 50
</style>
